package webserver;

import java.io.BufferedOutputStream;
import java.io.IOException;

/**
 * This class manages the Response for a given Request
 * It will be scheduled an automatically sent out by any Thread in a Threadpool
 * 
 */
// <editor-fold defaultstate="collapsed" desc=" UML Marker "> 
// #[regen=yes,id=DCE.1A32033F-4083-E393-2E32-70E075CC128B]
// </editor-fold> 
public class ResponseThread extends Thread {

	// Variables
	// <editor-fold defaultstate="collapsed" desc=" UML Marker ">
	// #[regen=yes,id=DCE.919B53C1-4349-DB3F-4ECF-5E8FB1931D95]
	// </editor-fold>
	private Request request;
	// <editor-fold defaultstate="collapsed" desc=" UML Marker ">
	// #[regen=yes,id=DCE.4E1894EF-08BC-84EC-547F-38E8BECB4E9E]
	// </editor-fold>
	private Server server;

	/**
	 * ResponseThread Default Constructor
	 * @param server - The server which has to send the Resoponse (parent)
	 * @param request - The Request which contains the Response
	 */
	// <editor-fold defaultstate="collapsed" desc=" UML Marker ">
	// #[regen=yes,id=DCE.3999FFC6-98C3-5A28-7F64-F1E7F3BE00F8]
	// </editor-fold>
	public ResponseThread(Server server, Request request) {
		this.server = server;
		this.request = request;
	}

	/**
	 * The implementation of the run Method
	 * This will be called to signal that the Response should now be sent
	 */
	@Override
	public void run() {
		// Generate Response
		this.request.generateResponse();

		// Try sending the Response
		try {
			BufferedOutputStream out = new BufferedOutputStream(this.request.getSocket().getOutputStream());

			out.write(this.request.getHeader());
			out.flush();
			byte data[] = this.request.getData();
			if (data != null) {
				out.write(data);
				out.flush();
			}

			Logger.writeToServerLog(this.request.getLogFileEntry());
		} catch (IOException io) {
			Logger.writeToLog("Error sending the Response for Request " + this.request.toString() + ": " + io.toString());
		} finally {
			this.server.finishedRequest(this, this.request);
		}
	}

	/**
	 * Tell the Thread to finish immediately
	 */
	public void finish() {
		System.out.println("Socket closed now");
		try {
			this.interrupt();

			this.request.finish();

		} catch (SecurityException se) {
			// ignore :)
		}
	}
}

